/**
 * 
 */
package com.demo.interceptor;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.demo.common.kit.WebUtils;
import com.demo.model.SysMenu;
import com.demo.service.MenuService;
import com.demo.service.RoleService;

/**
 * MenuInterceptor Description:
 * 
 * @author Zhuqingcheng
 * @date 2017年11月27日 下午1:49:51
 */
public class MenuInterceptor implements HandlerInterceptor {
	@Autowired
	private RoleService roleService;

	@Autowired
	private MenuService menuService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
		if (roleService == null) {// 解决service为null无法注入问题
			roleService = (RoleService) factory.getBean("roleServiceImpl");
		}
		if (menuService == null) {
			menuService = (MenuService) factory.getBean("menuServiceImpl");
		}
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if (!WebUtils.isAjax(request)) {
			HttpSession httpSession = request.getSession();
			List<SysMenu> menuList;
			menuList = (List<SysMenu>) httpSession.getAttribute("menu");
			if (menuList == null) {
				String username = SecurityUtils.getSubject().getPrincipal().toString();
				Integer roleId = roleService.findUserRole(username).getRoleId();
				menuList = menuService.findByRoleId(roleId);
				for (SysMenu menu : menuList) {
					List<SysMenu> children = new ArrayList<SysMenu>();
					for (SysMenu m : menuService.findAll(roleId)) {
						if (menu.getMenuId() == m.getParentId()) {
							children.add(m);
						}
						menu.setChildrenList(children);
					}
				}
				httpSession.setAttribute("menu", menuList);
			}
		}

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
